package utils;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class JdbcUtils {
    private  static String url;
    private  static String username;
    private  static String password;
    private  static String driver;
    private static Connection conn;
    static{
        try {
            Properties pro=new Properties();
            pro.load(JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            url=pro.getProperty("url");
            username=pro.getProperty("username");
            password=pro.getProperty("password");
            driver=pro.getProperty("driver");
            Class.forName(driver);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
    public static Connection getConnection(){
        if (conn==null){
            try {
                return DriverManager.getConnection(url,username,password);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return conn;
    }
    public static void close(Statement stmt, Connection conn){
        if (stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

    }
    public static void close(ResultSet rs, Statement stmt, Connection conn){
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
        if (stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

    }

}